package com.sskj.uboex.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.MoreLessBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.TipUtil;
import com.sskj.uboex.R;
import com.sskj.uboex.bean.AppVersionBean;
import com.sskj.uboex.presenter.MainActivityPresenter;
import com.sskj.uboex.ui.fragment.AppUpDateFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.ObservableEmitter;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

import static com.sskj.uboex.http.HttpConfig.BASE_URL;


@Route(path = RConfig.APP_MAIN)//主页面
public class MainActivity extends BaseActivity<MainActivityPresenter> {
    @BindView(R.id.bottomNavigationBar)
    BottomNavigationBar bottomNavigationBar;
    private List<Fragment> fragments;
    @Autowired
    int pos = 0;
    private boolean versionShow = false;  // 判断是否显示当前版本提示语

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_main;
    }

    @Override
    public MainActivityPresenter getPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    public boolean getImmersion() {
        return false;
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        initFragment();
        initBottomNavBar();
        RxBus.getDefault().register(this);
        mPresenter.initWebSocket();
        mPresenter.getNewVersion();
    }

//    @Subscribe(code = RxBusCode.CHANGE_LANGUAGE, threadMode = ThreadMode.MAIN)
//    public void changeLanguage() {
//        updateViewLanguage(findViewById(android.R.id.content));
//    }
//
//    //给给出一个view，把子view全部检查一遍，如果是实现LanguageView接口的view，更新语言
//    public static void updateViewLanguage(View view) {
//        if (view instanceof ViewGroup) {
//            ViewGroup vg = (ViewGroup) view;
//            int count = vg.getChildCount();
//            for (int i = 0; i < count; i++) {
//                updateViewLanguage(vg.getChildAt(i));
//            }
//        } else if (view instanceof TextView) {
//            TextView tv = (TextView) view;
//            tv.setText(tv.getText());
//        }
//    }

//    @Subscribe(code = RxBusCode.LOGIN, threadMode = ThreadMode.MAIN)
//    public void login() {
//        String id = SPUtil.get(SPConfig.ID, "");
//        if (!TextUtils.isEmpty(id)) {
//            OkGo.<HttpData<UserData>>get(BASE_URL + "/app/personalInformation/getUserInfo")
//                    .params("id", id)
//                    .execute(new JsonCallBack<HttpData<UserData>>() {
//                        @Override
//                        public void onSuccess(Response<HttpData<UserData>> response) {
//                            HttpData<UserData> httpData = response.body();
//                            if (httpData.getStatus() == BaseHttpConfig.OK) {
//                                if (TextUtils.isEmpty(httpData.getData().getTel())) {
//                                    try {
//                                        TipUtil.getTip(MainActivity.this, "1", false, () -> {
//                                        }).show();
//                                    } catch (Exception e) {
//
//                                    }
//                                }
//                            }
//                        }
//                    });
//        }
//    }


    public void initBottomNavBar() {
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_DEFAULT);
        bottomNavigationBar.setBarBackgroundColor(R.color.commonWhite);

        bottomNavigationBar.setActiveColor(R.color.apptabNormalColor)
                .addItem(new BottomNavigationItem(R.mipmap.hangqing_hover, "行情")
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.hangqing)))
                .addItem(new BottomNavigationItem(R.mipmap.heyue_hover, "合约")
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.heyue)))
                .addItem(new BottomNavigationItem(R.mipmap.changwai_hover, "场外交易")
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.changwai)))
                .addItem(new BottomNavigationItem(R.mipmap.caiwu_hover, "财务")
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.caiwu)))
                .addItem(new BottomNavigationItem(R.mipmap.wode_hover, "我的")
                        .setInactiveIcon(ContextCompat.getDrawable(MainActivity.this, R.mipmap.wode)))
                .setFirstSelectedPosition(pos).initialise();
        setTabSelection(pos);
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                setTabSelection(position);


            }

            @Override
            public void onTabUnselected(int position) {
            }

            @Override
            public void onTabReselected(int position) {
            }
        });
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            if (versionShow) {
                ToastUtil.showShort("当前已是最新版本，请放心使用");
            }
            return;
        }
        String verName = APKVersionCodeUtils.getVerName(this);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(versionBean.getAppVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    /*
     *初始化Fragment栈管理
     */

    public void initFragment() {
        Log.i("info","FDAFDAFADFAd");
        fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_HANGQING).withString(Constans.CODE, "3c_usdt").navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_MAIN).navigation());

        fragments.add((Fragment) ARouter.getInstance().build(RConfig.FABI_FRAGMENT).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_FINANCE).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.MINE_FRAGMENT_MAIN).navigation());
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        for (Fragment fragment : fragments) {
            transaction.add(R.id.frameLayout, fragment);
        }
        transaction.commit();
    }

    public void setTabSelection(int index) {
        // 开启一个Fragment事务
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(fragmentTransaction);
        fragmentTransaction.show(fragments.get(index));
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param fragmentTransaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        for (Fragment fragment : fragments) {
            fragmentTransaction.hide(fragment);
        }
    }

    @Override
    protected void onDestroy() {
        mPresenter.closeWebSocket();
        super.onDestroy();
    }

    /**
     * 个人中心校验版本更新
     */
    @Subscribe(code = RxBusCode.VERSION_UPDATE, threadMode = ThreadMode.MAIN)
    public void updateVersion() {
        mPresenter.getNewVersion();
        versionShow = true;
    }

    /**
     * K线图选择做多做空
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void chooseLevel(MoreLessBean moreLessBean) {
        bottomNavigationBar.selectTab(1);
    }
}